package edu.nf.vrs.announcement.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import edu.nf.vrs.announcement.dao.AnnouncementDao;
import edu.nf.vrs.announcement.dto.AnnouncementDTO;
import edu.nf.vrs.announcement.dto.AnnouncementPageDTO;
import edu.nf.vrs.announcement.entiy.Announcement;
import edu.nf.vrs.announcement.exception.AnnouncementException;
import edu.nf.vrs.announcement.inf.AnnouncementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Lv
 * @date 2022/4/6
 */
@Slf4j
@DubboService(interfaceClass = AnnouncementService.class,version = "1.0.0")
@Transactional(rollbackFor = RuntimeException.class)
public class AnnouncementServiceImpl implements AnnouncementService{

    @Autowired
    private AnnouncementDao announcementDao;

    /**
     * 查询所有公告
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public AnnouncementPageDTO listAnnouncement(Integer pageNum, Integer pageSize) {
        List<Announcement> list = announcementDao.listAnnouncement(pageNum, pageSize);
        PageInfo<Announcement> pageInfo = new PageInfo<>(list);
        AnnouncementPageDTO pageDTO = BeanUtil.copyProperties(pageInfo, AnnouncementPageDTO.class);
        return pageDTO;
    }

    /**
     * 添加公告
     * @param announcementDTO
     */
    @Override
    public void addAnnouncement(AnnouncementDTO announcementDTO) {
        try {
            Announcement announcement = BeanUtil.copyProperties(announcementDTO, Announcement.class);
            //获取当前时间
            //System.currentTimeMillis())方法获取时间的毫秒数，new Date()调用了System.currentTimeMillis方法。
            announcement.setCreateTime(new Date(System.currentTimeMillis()));
            announcementDao.addAnnouncement(announcement);
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new AnnouncementException("发布公告失败，请稍后重试！",e);
        }
    }

    /**
     * 更新公告
     * @param announcementDTO
     */
    @Override
    public void updateAnnouncement(AnnouncementDTO announcementDTO) {
        try {
            Announcement announcement = BeanUtil.copyProperties(announcementDTO, Announcement.class);
            announcementDao.updateAnnouncement(announcement);
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new AnnouncementException("更新公告失败，请稍后重试！",e);
        }
    }

    /**
     * 查询某公告
     * @param id
     * @return
     */
    @Override
    public AnnouncementDTO getAnnouncementById(Integer id) {
        Announcement announcement = announcementDao.getAnnouncementById(id);
        AnnouncementDTO dto = BeanUtil.copyProperties(announcement, AnnouncementDTO.class);
        return dto;
    }
}
